// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: MIT
use slint::{Model, Timer, TimerMode, VecModel};
use std::rc::Rc;
use std::time::{Duration, Instant};

slint::include_modules!();

fn startup_game(tiles: Vec<TileData>) -> std::rc::Rc<VecModel<TileData>> {
    use rand::seq::SliceRandom;
    use rand::SeedableRng;
    use rand_pcg::Pcg64;

    let mut tiles = tiles;
    tiles.extend(tiles.clone());

    let mut rng = rand::thread_rng();

    // let mut rng = Pcg64::seed_from_u64(2);
    tiles.shuffle(&mut rng);
    Rc::new(VecModel::from(tiles))
}

// #[allow(unused_variables)]
fn main() -> Result<(), slint::PlatformError> {
    let ui = AppWindow::new()?;

    let defalut_tiles: Vec<TileData> = ui.get_memory_tiles_default().iter().collect();
    let random_tiles_root = startup_game(defalut_tiles);

    ui.set_memory_tiles(random_tiles_root.clone().into());
    let game_time = Instant::now();

    // 退出游戏按钮
    {
        let weak_ui = ui.as_weak();
        ui.on_exit_game(move || {
            let ui = weak_ui.unwrap();
            ui.hide().unwrap();
        });
    }

    // 再来一把按钮
    {
        let weak_ui = ui.as_weak();
        ui.on_play_again(move || {
            let ui = weak_ui.unwrap();
            ui.invoke_close_welldone_window();

            let defalut_tiles: Vec<TileData> = ui.get_memory_tiles_default().iter().collect();

            let random_tiles = startup_game(defalut_tiles);
            for mut tile in random_tiles.iter() {
                tile.image_visible = false;
                tile.solved = false
            }

            ui.set_memory_tiles(random_tiles.into());
            ui.set_disable_tiles(false);

            let _solved_count: i32 = 0;
        });
    }

    // 显示所有按钮
    {
        let weak_ui = ui.as_weak();
        ui.on_show_all(move || {
            let ui = weak_ui.unwrap();
            let random_tiles = ui.get_memory_tiles();

            for (idx, mut tile) in random_tiles.iter().enumerate() {
                tile.image_visible = true;
                random_tiles.set_row_data(idx, tile);
            }
            // ui.set_memory_tiles(random_tiles.clone());
            weak_ui.unwrap().set_disable_tiles(true);

            let weak_ui = ui.as_weak();
            Timer::single_shot(Duration::from_secs(1), move || {
                weak_ui.unwrap().set_disable_tiles(false);
                for (idx, mut tile) in random_tiles.iter().enumerate() {
                    tile.image_visible = false;
                    random_tiles.set_row_data(idx, tile);
                }
            })
        })
    }

    // 检查配对
    {
        let weak_ui = ui.as_weak();
        ui.on_check_if_pair_solved(move || {
            let ui = weak_ui.unwrap();

            let random_tiles = ui.get_memory_tiles();

            // BUG 第二回合后无法生效
            let mut flipped_tiles = random_tiles
                .iter()
                .enumerate()
                .filter(|(_, tile)| tile.image_visible && !tile.solved);

            if let (Some((r_id1, mut t1)), Some((r_id2, mut t2))) =
                (flipped_tiles.next(), flipped_tiles.next())
            {
                if t1 == t2 {
                    t1.solved = true;
                    t2.solved = true;
                    random_tiles.set_row_data(r_id1, t1);
                    random_tiles.set_row_data(r_id2, t2);
                } else {
                    weak_ui.unwrap().set_disable_tiles(true);
                    let weak_ui = weak_ui.clone();
                    let random_tiles = random_tiles.clone();
                    Timer::single_shot(Duration::from_secs(1), move || {
                        weak_ui.unwrap().set_disable_tiles(false);
                        t1.image_visible = false;
                        t2.image_visible = false;
                        random_tiles.set_row_data(r_id1, t1);
                        random_tiles.set_row_data(r_id2, t2);
                    })
                }
            }

            // 检查是否全部已经解决
            let tiles_count = random_tiles.iter().filter(|tile| tile.solved).count();
            println!("Solved: {}", tiles_count);
            if tiles_count == 16 {
                for (_, mut tile) in random_tiles.iter().enumerate() {
                    tile.solved = false;
                    tile.image_visible = false;
                }
                let time = game_time.elapsed().as_secs();
                ui.set_game_time(format!("总耗时：{}秒~", time).into());
                ui.invoke_show_welldone_window();
            }
        });
    }
    ui.run()
}
